//
//  LoginViewController.m
//  Exchange
//
//  Created by 张庆勇 on 2018/7/18.
//  Copyright © 2018年 张庆勇. All rights reserved.
//
#import "LoginViewController.h"
#import "RegisterViewController.h"
@interface LoginViewController ()
@end
@implementation LoginViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    
    if ([[EXUnit getSite] isEqualToString:@"ZG"])
    {
        [_icon setImage:[UIImage imageNamed:@"ZG_launchImg"] forState:0];
    }else if ([[EXUnit getSite] isEqualToString:@"ZT"])
    {
        [_icon setImage:[UIImage imageNamed:@"ZT_launchImg"] forState:0];
    }else if ([[EXUnit getSite] isEqualToString:@"58"])
    {
        [_icon setImage:[UIImage imageNamed:@"58_launchImg"] forState:0];
    }else if ([[EXUnit getSite] isEqualToString:@"人人币"])
    {
        [_icon setImage:[UIImage imageNamed:@"rrb_launchImg"] forState:0];
    }else if ([[EXUnit getSite] isEqualToString:@"KCoin"])
    {
        [_icon setImage:[UIImage imageNamed:@"Kcoin_launchImg"] forState:0];
    }else if ([[EXUnit getSite] isEqualToString:@"BitAladdin"])
    {
        [_icon setImage:[UIImage imageNamed:[ZBLocalized sharedInstance].bitAladdinLaunchImg] forState:0];
    }else if ([[EXUnit getSite] isEqualToString:@"ZGK"])
    {
        [_icon setImage:[UIImage imageNamed:@"zgk_launchImg"] forState:0];
    }else if ([[EXUnit getSite] isEqualToString:@"GEMEX"])
    {
        [_icon setImage:[UIImage imageNamed:@"GEMEX_launchImg"] forState:0];
    }else if ([[EXUnit getSite] isEqualToString:@"GitBtc"])
    {
        
        [_icon setImage:[UIImage imageNamed:@"GitBtc_launchImg"] forState:0];
    }else if ([[EXUnit getSite] isEqualToString:@"ACE"])
    {
        
        [_icon setImage:[UIImage imageNamed:@"ACE_launchImg"] forState:0];
        
    }else if ([[EXUnit getSite] isEqualToString:@"Rockex"])
    {
        
        [_icon setImage:[UIImage imageNamed:@"Rockex_launchImg"] forState:0];
        
    }else if ([[EXUnit getSite] isEqualToString:@"Coinbetter"])
    {
        
        [_icon setImage:[UIImage imageNamed:[ZBLocalized sharedInstance].CoinbetterLoginIcon] forState:0];
    }else if ([[EXUnit getSite] isEqualToString:@"Comex"])
    {
        
        [_icon setImage:[UIImage imageNamed:@"Comex_launchImg"] forState:0];
        
    }else if ([[EXUnit getSite] isEqualToString:@"Ex.pizza"])
    {
        [_icon setImage:[UIImage imageNamed:@"ex.pizza_launchImg"] forState:0];
    }
    [self initUI];
}
- (void)initTextFieldWithTextField:(UITextField *)TextField placeholder:(NSString *)placeholder
{
    TextField.font = AutoBoldFont(15);
    TextField.placeholder = placeholder;
    [TextField setValue:textFieldPCOLOR forKeyPath:@"_placeholderLabel.textColor"];
    [TextField setValue:AutoFont(15) forKeyPath:@"_placeholderLabel.font"];
    TextField.tintColor = TABTITLECOLOR;
    TextField.textColor = MAINTITLECOLOR;
    
}
- (void)initUI
{
    self.view.backgroundColor = MAINBLACKCOLOR;
    _linePW.backgroundColor = CELLCOLOR;
    _lineACO.backgroundColor = CELLCOLOR;
    [_returnbutton setImage:[UIImage imageNamed:[ZBLocalized sharedInstance].loginbackicon] forState:0];
    [_forgetPwbutton setTitleColor:[ZBLocalized sharedInstance].TabBgColor forState:0];
    [_forgetPwbutton setTitle:Localized(@"login_Forget_password") forState:0];
    _forgetPwbutton.titleLabel.lineBreakMode = 0;//这句话很重要，不加这句话加上换行符也没
    _forgetPwbutton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    
    _loginButton.backgroundColor = [ZBLocalized sharedInstance].TabBgColor;
    
    [_loginButton setTitle:Localized(@"login") forState:0];
    _loginButton.titleLabel.font = AutoBoldFont(15);
    
    [self initTextFieldWithTextField:_PhoneField placeholder:Localized(@"login_account_number")];
    
    _PhoneField.text = [(NSMutableDictionary *)[CHKeychain load:KEY_USERNAME_PASSWORD] objectForKey:KEY_USERNAME];
    [self initTextFieldWithTextField:_passwordField placeholder:Localized(@"login_password_message")];
    
    _registerLable.attributedText = [EXUnit finderattributedString:Localized(@"login_No_account") attributedString:Localized(@"login_Fast_registration") color:[ZBLocalized sharedInstance].TabBgColor font:AutoFont(13)];
    KViewRadius(self.loginButton, 2);
    if ([[ZBLocalized sharedInstance].currentLanguage hasPrefix:@"zh-H"])
    {
        _registerLable.textAlignment = NSTextAlignmentRight;
    }else
    {
        _registerLable.textAlignment = NSTextAlignmentLeft;
    }
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
    [[tap rac_gestureSignal] subscribeNext:^(id x) {
        RegisterViewController *RegisterVc = [[RegisterViewController alloc]init];
        RegisterVc.isRegister = YES;
        [self presentViewController:RegisterVc animated:YES completion:nil];
    }];
    _registerLable.userInteractionEnabled = YES;
    [_registerLable addGestureRecognizer:tap];
    
    
    RACSignal*phone=[_PhoneField.rac_textSignal map:^id(NSString* value) {
        return  @(value.length>0);
    }];
    RACSignal*validPswSignal=[_passwordField.rac_textSignal map:^id(NSString* value) {
        return @(value.length>PassworldLastlength && value.length<Passworldhighlength);
    }];
    RACSignal*loginSignal=[RACSignal combineLatest:@[phone,validPswSignal] reduce:^id(NSNumber*phoneValid,NSNumber*pswValid){
        return @([phoneValid boolValue]&&[pswValid boolValue]);
    }];
    WeakSelf
    [loginSignal subscribeNext:^(NSNumber* x) {
        if ([x boolValue]) {
            weakSelf.loginButton.enabled=YES;
            weakSelf.loginButton.alpha = 1;
            weakSelf.loginButton.backgroundColor = TABTITLECOLOR;
            [weakSelf.loginButton setTitleColor:[UIColor whiteColor] forState:0];
        }else{
            weakSelf.loginButton.enabled=NO;
            weakSelf.loginButton.alpha = 1;
            weakSelf.loginButton.backgroundColor = [ZBLocalized sharedInstance].buttonNormalStatus;
            [weakSelf.loginButton setTitleColor:ColorStr(@"#AAAAAA") forState:0];
        }
    }];
    [weakSelf.loginButton add_BtnClickHandler:^(NSInteger tag) { //登陆
        if (![weakSelf.PhoneField.text isEqualToString:[(NSMutableDictionary *)[CHKeychain load:KEY_USERNAME_PASSWORD] objectForKey:KEY_USERNAME]]) //判断账号如果不是上次登录账号删除本地收藏和手势验证功能
        {
            [EXUnit deletaCollectionData];//删除收藏
            [EXUserManager saveIsTouchid:@"0"];//删除指纹
            [EXUserManager saveIsGesture:@"0"];//删除手势
        }
        if ([EXUnit judgePassWordLegal:weakSelf.passwordField.text]) {
            NSString *uuid = [[NSUUID UUID] UUIDString];
            NSDictionary * loginDic = @{@"username":weakSelf.PhoneField.text,
                                        @"password":weakSelf.passwordField.text,
                                        @"is_app":@"1",
                                        @"client_id":@"",
                                        @"platform":@"ios",
                                        @"app_version":[EXUnit getVersion],
                                        @"os_version": [[UIDevice currentDevice] systemVersion],
                                        @"device_id": uuid,
                                        };
            
            [weakSelf POSTWithHost:@"" path:loginHttp param:loginDic cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                [weakSelf.loginButton stopAnimation];
                if ([responseObject[@"code"] integerValue]==0)//成功
                {
                    NSDictionary * userdic = responseObject[@"result"];
                    //                    0 表示不需要安全登录验证， 1 表示需要
                    NSInteger need_safe = [userdic[@"need_safe"] integerValue];
                    
                    NSArray * result = userdic[@"user_securities"];
                    [EXUserManager savephone:@"0"];
                    [EXUserManager saveemail:@"0"];
                    [EXUserManager saveGoole:@"0"];
                    for (NSDictionary * dic in result) {
                        
                        if ([dic[@"type"] integerValue] ==1)
                        {
                            [EXUserManager savephone:@"1"];
                        }else if ([dic[@"type"] integerValue] ==0)
                        {
                            [EXUserManager saveemail:@"1"];
                        }else if ([dic[@"type"] integerValue] ==2)
                        {
                            [EXUserManager saveGoole:@"1"];
                        }
                    }
                    if (need_safe ==1)
                    {
                        [EXUserManager saveUserInfo:[EXUser mj_objectWithKeyValues:userdic]];
                        [EXUserManager savepersonalData:[Userinfo mj_objectWithKeyValues:userdic]];
                        [weakSelf.PhoneField resignFirstResponder];
                        [weakSelf.passwordField resignFirstResponder];
                        [self safeLogin];
                    }else if (need_safe ==0)
                    {
                        [self jsonAnalyticData:responseObject[@"result"]];
                    }
                    
                }else
                {
                    [self axcBasePopUpWarningAlertViewWithMessage:responseObject[@"message"] view:kWindow];
                }
            } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                [weakSelf.loginButton stopAnimation];
                
            }];
        }else
        {
            [weakSelf.loginButton stopAnimation];
            [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"login_Illegal_password") view:kWindow];
        }
    }];
}
- (void)safeLogin
{
    
    CustomAlertVC * custom = [[CustomAlertVC alloc] initWithCustomContentViewClass:@"BindCustonAlert" delegate:nil];
    custom.direction = FromBottom;
    [custom show];
    BindCustonAlert *aleatView = (BindCustonAlert *)custom.contentView;
    aleatView.type = @"1";
    aleatView.isBindGoole = NO;
    aleatView.cancelBlock = ^{
        [custom dismiss];
    };
    
    WeakSelf
    WeakObject(aleatView)
    
    [aleatView.okButton add_BtnClickHandler:^(NSInteger tag) {
        
        if (![NSString isEmptyString:weakaleatView.emailField.text])
        {
            if (![EXUnit CodeissSixplace:weakaleatView.emailField.text]) {
                
                [EXUnit showMessage:Localized(@"VerificationMessage")];
                return ;
            }
        }
        if (![NSString isEmptyString:weakaleatView.phoneField.text])
        {
            if (![EXUnit CodeissSixplace:weakaleatView.phoneField.text]) {
                [EXUnit showMessage:Localized(@"VerificationMessage")];
                return ;
            }
        }
        NSDictionary * param = @{
                                 @"sms_code":[NSString isEmptyString:weakaleatView.phoneField.text]?@"":weakaleatView.phoneField.text,
                                 @"email_code":[NSString isEmptyString:weakaleatView.emailField.text]?@"":weakaleatView.emailField.text,
                                 @"two_step_code":[NSString isEmptyString:weakaleatView.gooldField.text]?@"":weakaleatView.gooldField.text};
        
        [weakSelf POSTWithHost:@"" path:safeLogin param:param cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            [weakaleatView.okButton stopAnimation];
            if ([responseObject[@"code"] integerValue]==0)//成功
            {
                [custom dismiss];
                
                [self jsonAnalyticData:responseObject[@"result"]];
                
            }else
            {
                [weakSelf axcBasePopUpWarningAlertViewWithMessage:responseObject[@"message"] view:kWindow];
            }
            
        } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            [weakaleatView.okButton stopAnimation];
        }];
        
    }];
}
//数据解析
- (void)jsonAnalyticData:(NSDictionary *)dic
{
    [EXUserManager saveUserInfo:[EXUser mj_objectWithKeyValues:dic]];
    
    [AppDelegate shareAppdelegate].isBecomeActive = NO;
    //  记住账号和密码
    NSMutableDictionary *usernamepasswordKVPairs = [NSMutableDictionary dictionary];
    [usernamepasswordKVPairs setObject:self.PhoneField.text forKey:KEY_USERNAME];
    [CHKeychain save:KEY_USERNAME_PASSWORD data:usernamepasswordKVPairs];
    //    储存登录变量
    [EXUserManager savelogin:@"1"];
    
    NSArray * dataArray1  = @[[EXUserManager userInfo].token,@"ios"];
    NSData *data1 = [EXUnit NSJSONSerializationWithmethod:@"server.auth" parameter:dataArray1 id:1763];
    [[SocketRocketUtility instance] sendData:data1];    // 发送数据
    [[NSNotificationCenter defaultCenter] postNotificationName:LoginSusessNotificationse object:nil];
    [EXUserManager getbindInfo:^(BOOL isSuccess) {
        
    }];
    
    [self dismissAnimation];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)forgetPwButton:(UIButton *)sender {
    
    RegisterViewController *RegisterVc = [[RegisterViewController alloc]init];
    RegisterVc.isRegister = NO;
    [self presentViewController:RegisterVc animated:YES completion:nil];
    
}

- (IBAction)deletebutton:(UIButton *)sender {
    
    self.PhoneField.text = nil;
}

- (IBAction)openPassword:(UIButton *)sender {
    sender.selected = !sender.selected;
    self.passwordField.secureTextEntry = !self.passwordField.secureTextEntry;
    //    self.passwordField.enabled =! self.passwordField.enabled;
}

- (IBAction)returnHome:(UIButton *)sender {
    [self dismissAnimation];
}
- (void)dismissAnimation
{
    CATransition *myTra = [CATransition animation];
    myTra.duration = 0.5;
    myTra.type = kCATransitionMoveIn;
    [self.view.superview.layer addAnimation:myTra forKey:nil];
    
    //水波动效果
    CATransition *transition = [CATransition animation];
    
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
    transition.duration = 1.5f;
    transition.type = @"rippleEffect";
    
    [self.view.window.layer addAnimation:transition forKey:@"rippleEffect"];
    [self dismissViewControllerAnimated:YES completion:nil];
}
@end
